//
//  HomeTableViewController.swift
//  WeiBo001
//
//  Created by Zhanghong on 15/6/26.
//  Copyright © 2015年 HeiMa. All rights reserved.
//

import UIKit
import SVProgressHUD
import SDWebImage




class HomeTableViewController: BaseTableViewController {
    lazy var rowHeightCache = [Int: CGFloat]()
    var statusesList: [Status]? {
        didSet{
            // 刷新表格
            tableView.reloadData()
            
            refreshControl?.endRefreshing()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        visitorView?.setupViewInfo("visitordiscover_feed_image_house", message: "关注一些人，回这里看看有什么惊喜", isHome: true)
        
        if !userlogin {
            return
        }
    
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None

        setupNavigationBar()
        prepareTableView()
        loadData()
        
        refreshControl = HMRefreshController()
        
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        
    }
    
    func loadData(){
        let since_id = statusesList?.first?.id ?? 0
        Status.loadStatus(since_id) {(statuses,error) -> () in
            if error != nil {
                // 不要把错误的相信信息告诉用户，程序员应该多测试！
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                return
            }
            
            // 提示，后续会有下拉刷新，没有新微博的情况，不要抱错！
            if statuses == nil {
                print("没有数据")
                return
            }
            
//            for s in statuses! {
//                if s.retweeted_status != nil {
//                    print("转发微博")
//                }
//            }
            
            print("加载了\(statuses?.count)条微博")
            if since_id > 0 {
                self.statusesList = statuses! + self.statusesList!
            } else {
                self.statusesList = statuses
            }
            
            //self.statusesList = statuses
        }
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        visitorView?.startAnimation()
    }
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//        print("行数----------------\(statusesList?.count)")
        return statusesList?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let status = statusesList![indexPath.row]

        if self.rowHeightCache[status.id] != nil {
            print("返回缓存行高")
            return rowHeightCache[status.id]!
        }
        
        let ID = StatusCell.cellIdentifier(status)
        var cls: AnyClass = StatusNormalCell.self
        if ID == HMStatusForwardCellIdentifier {
            cls = StatusForwardCell.self
        }
        let cell = cls.new() as! StatusCell
        //let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! StatusCell
        let height = cell.rowHeight(status)
        rowHeightCache[status.id] = height
        return height
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! StatusCell
//        cell.status = statusesList![indexPath.row]
//        return cell
        let status = statusesList![indexPath.row]
        let ID = StatusCell.cellIdentifier(status)
        let cell = tableView.dequeueReusableCellWithIdentifier(ID, forIndexPath: indexPath) as! StatusCell
        cell.status = status
        return cell
    }
    
    
    func titleButtonClicked() {
        let sb = UIStoryboard(name: "FriendGroup", bundle: nil)
        let vc = sb.instantiateViewControllerWithIdentifier("FriendGroup")
        
        let popoverAnimator = PopoverAnimator()
        vc.transitioningDelegate = popoverAnimator
        
        let x = (view.bounds.width - 200) * 0.5
        popoverAnimator.presentFrame = CGRectMake(x, 56, 200, 240)
        
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        presentViewController(vc, animated: true, completion: nil)
        
    }
    
    func ShowQRCode(){
        let sb = UIStoryboard(name: "QRCode", bundle: nil)
        presentViewController(sb.instantiateInitialViewController()!, animated: true, completion: nil)
    }
    
    private func setupNavigationBar(){
        if shareAccount == nil {
            return
        }
        
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", hilightedImageName: nil)
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", hilightedImageName: nil)
        
        let btn = navigationItem.rightBarButtonItem?.customView as! UIButton
        btn.addTarget(self, action: "ShowQRCode", forControlEvents: UIControlEvents.TouchUpInside)
       
        
   
        let name = shareAccount!.name!
        let titleButton = HomeTitleButton.button(name)
      
        
        titleButton.addTarget(self, action: "titleButtonClicked", forControlEvents: UIControlEvents.TouchUpInside)
        
        navigationItem.titleView = titleButton
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
        // 清空缓存，提示：NSCache 不能清空
        rowHeightCache.removeAll()
    }
    
    private func prepareTableView(){
        tableView.registerClass(StatusForwardCell.self, forCellReuseIdentifier: HMStatusForwardCellIdentifier)
        tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: HMStatusNormalCellIdentifier)
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
    }
    
}














